'''
Created on Jul 18, 2012

@author: thomas_dao
'''
'''
Created on Jul 17, 2012

@author: daoxuandung
'''
from web import base
from web.base import BaseHandler
from web import urls
from kid import util
import json
import logging
from google.appengine.ext import ndb
from entity.entity import Article, Vote
from app import article_async, article_stat

class CreateHandler(BaseHandler):
    @ndb.synctasklet
    @base.user_required
    def post(self):        
        # Get input data
        vote_up = self.request.params.get('up')
        if vote_up == 'true':
            vote_up = True
            
        elif vote_up == 'false':
            vote_up = False
        
        article_id = self.request.params.get('article_id')
        article_key = ndb.Key(Article, int(article_id))
 
        # If user already created vote, toggle the vote
        user_key = util.get_current_user_key()
        qry = Vote.query(Vote.user == user_key, Vote.article == article_key)
        existed_vote = yield qry.get_async()
        if existed_vote:
            logging.info("exited_vote")
            
            # If user toggle (click same button)
            if existed_vote.up is not None and existed_vote.up == vote_up:
                existed_vote.up = None
            
            else: 
                existed_vote.up = vote_up
                
            existed_vote.put()
        else:
            # Create new entity and save
            vote = Vote()
            vote.up = vote_up
            vote.user = util.get_current_user_key()
            vote.article = article_key
            vote.put()
            
        # Response
        data = {}
        (vote_up, vote_down) = yield article_stat.get_vote_stats_async(article_key)
        data['vote_up'] = vote_up
        data['vote_down'] = vote_down
        self.response.write(json.dumps(data))

class ReadHandler(BaseHandler):
    def get(self):
        pass    

class UpdateHandler(BaseHandler):
    def post(self):        
        pass
    

class DeleteHandler(BaseHandler):
    def post(self):
        pass

app = urls.app

def main():
    app.run()

if __name__ == '__main__':
    main()